<template>
	<div @click="shows = false">
		<!-- xpert导航栏 -->
		<xpertNavBar :statusTab="statusTab" />
		<div style="height: 150px; width: 100%"></div>
		<div class="myClub m1280">My club</div>
		<div class="boxItem m1280 f f-j-b">
			<div class="left f f-d-c f-a-c f-j-c">
				<img style="object-fit: cover" :src="form.clubImage || ''" alt="" />
				<!-- edit上传头像 -->
				<div class="btnsss f f-j-c">
					<el-upload v-model:file-list="avaList" :headers="uploadHeaders" :action="baseUrl + '/knowclub-api/common/file/upload'" :on-success="successImg">
						<el-button style="border: none" class="ctrue hand">Edit picture</el-button>
						<!-- <el-button class="edit" type="primary">Edit</el-button> -->
					</el-upload>
				</div>
				<div class="title">Analytical Squad</div>
				<div class="tabs">
					<div :class="{ act: ind == 1 }" @click="ind = 1" class="tabsTop hand">Club</div>
					<div :class="{ act: ind == 2 }" @click="tow()" class="tabsTop hand">Content</div>
				</div>
			</div>
			<!-- 第一个 -->
			<div v-show="ind == 1">
				<div class="right">
					<div class="topName f f-a-c f-j-b">
						<div class="nameLef">
							<div class="tit">Club name</div>
							<input type="text" v-model="form.name" class="inp" placeholder="Analytical Squad" name="" id="" />
						</div>
						<div class="nameRig">
							<div style="margin-bottom: 12px" class="tit">Tags</div>
							<el-select v-model="form.tags" multiple placeholder="Select" size="large" style="width: 450px">
								<el-option v-for="item in port.tagList" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</div>
					<div style="margin-top: 25px" class="topName f f-a-c f-j-b">
						<div class="nameLef">
							<div style="margin-bottom: 12px" class="tit">Sector</div>
							<el-select v-model="form.sector" @change="chasngeSector" placeholder="Select option" size="large" style="width: 450px">
								<el-option v-for="item in sector" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
						<div class="nameRig">
							<div style="margin-bottom: 12px" class="tit">Industry</div>
							<el-select v-model="form.industry" placeholder="Select option" size="large" style="width: 450px">
								<el-option v-for="item in industry" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</div>
					<div class="price">Price</div>
					<div class="topName f f-a-c f-j-b">
						<div class="nameLef">
							<div class="tit">For subscription</div>
							<div class="inpBox f f-a-c f-j-b">
								<div style="width: 80%" class="f f-a-c">
									<div class="lefDao">$</div>
									<input type="text" v-model="form.subscription" class="pricInp" name="" id="" />
								</div>
								<div class="money">/Monthly</div>
							</div>
						</div>
						<div class="nameLef">
							<div class="tit">Offer discount</div>
							<div class="inpBox f f-a-c f-j-b">
								<div style="width: 80%" class="f f-a-c">
									<div class="lefDao">$</div>
									<input type="text" v-model="form.discount" class="pricInp" name="" id="" />
								</div>
								<div @click.stop="shows = true" class="money hand">
									/{{ Monthly }}
									<div v-show="shows" class="monryBox">
										<div @click.stop="qiehuan(3)" class="month hand">3 months</div>
										<div @click.stop="qiehuan(6)" class="month hand">6 months</div>
										<div @click.stop="qiehuan(12)" class="month hand">12 months</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					<!-- 下面的文本域 -->
					<div class="textInp">
						<div class="titText">Introduction</div>
						<a-textarea class="textarea" showCount :maxlength="150" v-model:value="form.introduction" placeholder="Please enter..." :auto-size="{ minRows: 4, maxRows: 10 }" />
					</div>
					<!-- 下面的文本域 -->
					<div class="textInp">
						<div class="titText">Description</div>
						<a-textarea class="textarea" showCount :maxlength="1000" v-model:value="form.description" placeholder="Please enter..." :auto-size="{ minRows: 8, maxRows: 10 }" />
					</div>
					<div class="save f f-a-c">
						<div @click="saveBao" class="saves hand">Save</div>
					</div>
				</div>
			</div>
			<!-- 第二个 -->
			<div v-show="ind == 2 && art == 1" class="right2">
				<div class="topFilter f f-a-c f-j-b">
					<div class="inpFilter f f-a-c">
						<div class="inpBoxs f f-a-c f-j-b">
							<input type="text" class="digtal" placeholder="Digital marketing" v-model="marking" name="" id="" />
							<img src="/src/assets/user/sousuo2.png" @click="sousuo" class="sousuo hand" alt="" />
						</div>
						<div @click="filterVisible = true" class="filters hand f f-a-c f-j-c">Filter <img src="/src/assets/user/list.png" alt="" /></div>
					</div>
					<div @click="addAct" class="add hand">+ Write an article</div>
				</div>
				<!-- thisMonth -->
				<div class="thisMonth">
					<!-- <div class="top">This month</div> -->
					<div v-for="(item, index) in port.list" :key="index">
						<div style="margin-bottom: 16px; margin-top: 40px; color: #8590a1; font-size: 14px" class="">
							{{
								item[0] == "1月"
									? "jan"
									: item[0] == "2月"
									? "feb"
									: item[0] == "3月"
									? "mar"
									: item[0] == "4月"
									? "apr"
									: item[0] == "5月"
									? "may"
									: item[0] == "6月"
									? "jun"
									: item[0] == "7月"
									? "jul"
									: item[0] == "8月"
									? "aug"
									: item[0] == "9月"
									? "sep"
									: item[0] == "10月"
									? "oct"
									: item[0] == "11月"
									? "nov"
									: "dec"
							}}
						</div>
						<div v-for="(ite, ind) in item[1]" :key="ind" class="thisItem f">
							<div class="title">
								<div class="titName">Title</div>
								<div class="howAl f f-a-c">{{ ite.title }}</div>
							</div>
							<div class="tags">
								<div class="titName">Tags</div>
								<div class="tagCoun f f-a-c f-w-w f-j-c">
									<div v-for="(it, inds) in ite.tags" :key="inds" class="tagItem">{{ it }}</div>
								</div>
							</div>
							<div class="price">
								<div class="titName f f-a-c f-j-c">Price <img src="/src/assets/user/wen.png" class="wenxImg" alt="" /></div>
								<div class="Mb">${{ ite.price || 0 }}/Mo</div>
							</div>
							<div class="price">
								<div class="titName f f-a-c f-j-c">Income <img src="/src/assets/user/wen.png" class="wenxImg" alt="" /></div>
								<div class="Mb">${{ ite.income }}</div>
							</div>
							<div class="pinned hand">
								<div @click="pinneds(ite)" :class="{ active: ind == indsValue }" @mouseover="handleMouseOver(ind)" @mouseleave="handleMouseLeave(ind)" class="titName">
									<img v-if="indsValue == ind" src="/src/assets/come/13.png" alt="" />
									<img v-else src="/src/assets/come/12.png" alt="" />
									Pinned
								</div>
								<div class="btnPin f f-a-c">
									<div @click="deletes(ite)" class="det hand">Delete</div>
									<div @click="edits(ite)" class="emit hand">Edit</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<!--  -->
				<div v-if="total" class="hand">
					<div class="example-pagination-block f f -a-c f-j-c">
						<el-pagination @size-change="sizeChange" :default-page-size="5" @current-change="currentChange" layout="prev, pager, next" :total="total" />
					</div>
				</div>
			</div>
			<!-- 新增 -->
			<div v-show="ind == 2 && art == 2" class="right3">
				<div class="write">Write an article</div>
				<div class="nameLef">
					<div class="tit">Title</div>
					<input type="text" v-model="title" class="inp" placeholder="How AI is Evolving" name="" id="" />
				</div>
				<div class="nameLef">
					<div style="margin-bottom: 12px" class="tit">Tags</div>
					<el-select v-model="tags" multiple placeholder="Select" size="large" style="width: 100%">
						<el-option v-for="item in port.articleList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>
				<div class="nameLef">
					<div class="tit">Article cover</div>
					<div>
						<el-upload v-model:file-list="fileList" limit="1" :headers="uploadHeaders" :on-success="successCover" :action="baseUrl + '/knowclub-api/common/file/upload'" list-type="picture-card">
							<el-icon><Plus /></el-icon>
						</el-upload>
					</div>
					<div class="counts">Only JPG/PNG/GIF is supported, and the size cannot exceed 1 MB, The recommended size is 800X600.</div>
				</div>
				<div class="priceOne">
					<div class="priceName">Price</div>
					<div class="pricBox f f-a-c">
						<div style="margin-right: 40px" @click="forFree" class="leftPic hand f f-a-c">
							<img v-if="showPrice == 1" src="/src/assets/user/gou.png" alt="" />
							<img v-else src="/src/assets/user/weigou.png" alt="" />
							For free
						</div>
						<div @click="showPrice = 2" class="leftPic hand f f-a-c">
							<img v-if="showPrice == 2" src="/src/assets/user/gou.png" alt="" />
							<img v-else src="/src/assets/user/weigou.png" alt="" />
							One time
						</div>
						<div class="inpBox f f-a-c">
							<div class="daola">$</div>
							<input type="text" :disabled="showPrice == 1" v-model="priceNum" placeholder="price" class="inpPrice" name="" id="" />
						</div>
					</div>
				</div>
				<!-- 下面的富文本 -->
				<div v-if="showPrice == 2" class="richText">
					<div class="topText">Preview content</div>
					<RichText ref="richText" :value="emailForm.test_msg" @updateValue="getMsg" />
				</div>
				<!-- 下面的富文本 -->
				<div class="richText">
					<div class="topText">Content</div>
					<RichText ref="richTexts" :value="emailForm.msg" @updateValue="getMsgs" />
				</div>
				<!-- btn -->
				<div class="botBtn f f-a-c">
					<div class="btn f f-a-c">
						<div @click="saveArt" class="lefBtn hand">Save</div>
						<div @click="priCount" class="rigBtn hand">Preview</div>
					</div>
				</div>
			</div>
		</div>
		<el-dialog v-model="filterVisible" title="" width="540px">
			<div class="filterTit">Filter</div>
			<div style="margin-bottom: 24px">
				<div class="titName">Date</div>
				<el-date-picker v-model="formFilter.dataTime" @change="changeFn" type="date" placeholder="Pick a day" size="large" />
			</div>
			<div style="margin-bottom: 24px">
				<div class="titName">Tags</div>
				<el-select v-model="formFilter.tags" size="large" multiple placeholder="Select" style="width: 100%">
					<el-option v-for="item in port.articleList" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</div>
			<div style="margin-bottom: 24px">
				<div class="titName">Tags</div>
				<div class="priceNum f f-a-c f-j-b">
					<div class="pricMin f f-a-c f-j-b">
						<span class="name">MIN</span>
						<input type="text" v-model="formFilter.min" class="pricInp" ame="" id="" />
						<span class="daola">$</span>
					</div>
					<div>-</div>
					<div class="pricMin f f-a-c f-j-b">
						<span class="name">MAX</span>
						<input type="text" v-model="formFilter.max" class="pricInp" ame="" id="" />
						<span class="daola">$</span>
					</div>
				</div>
			</div>
			<div class="btnB f f-a-c f-j-b">
				<div @click="cler" class="clear hand">Clear all</div>
				<div @click="sousuo" class="apply hand">Apply</div>
			</div>
		</el-dialog>
		<el-dialog v-model="dialogVisible">
			<img w-full :src="dialogImageUrl" alt="Preview Image" />
		</el-dialog>
		<xpertTabbar />
	</div>
</template>

<script setup>
	import RichText from "@/components/richText/index.vue";
	import { Plus } from "@element-plus/icons-vue";
	import { ClassificationTree } from "@/api/commonality.js";
	import { baseUrl } from "@/utils/setting.js";
	import { ElMessage, dayjs } from "element-plus";
	import {
		SellCreateClub,
		SellTagsList,
		CreateArticleList,
		DeleteleEcho,
		UpdateArticles,
		CreateAnArticle,
		GetArticleEcho,
		InformationAboutClubs,
		UpdateTheClub,
		PutArticleTheTop
	} from "@/api/knowClub/index.js";
	import { ref, onMounted, reactive, onActivated } from "vue";
	import { useRoute } from "vue-router";
	import xpertTabbar from "@/components/tabBar/xpertTabbar.vue";
	import xpertNavBar from "@/components/navBar/xpertNavBar.vue";

	import router from "@/router/index.js";
	import ButtonDiffuse from "@/components/Button/ButtonDiffuse.vue";
	let token = null;
	let route = useRoute();
	let indsValue = ref(-1);
	let clubId = route.query.clubId;
	let numInde = localStorage.getItem("home") || 1;
	if (numInde == 1) {
		// 代表是xpert首页
		token = "Bearer " + localStorage.getItem("xpToken") || "";
	} else {
		// 代表是knowClub首页
		token = "Bearer " + localStorage.getItem("kcToken") || "";
	}
	const uploadHeaders = ref({
		"Authorization-Kc": token
	});
	let statusTab = ref(1);
	let filterVisible = ref(false);
	let disabled = ref(true);
	const avaList = ref([]);
	let ind = ref(1);
	let time = ref("");
	let Monthly = ref("3 Monthly");
	let fileList = ref([]);
	let publishTime = ref("");
	let formFilter = reactive({
		dataTime: "",
		tags: [],
		min: "",
		max: ""
	});
	let richText = ref(null);
	let richTexts = ref(null);
	let art = ref(1);
	let inds = ref(1);
	let showPrice = ref(1);
	let id = ref(0);
	let marking = ref("");
	let imgCover = ref("");
	let MonthlyNum = ref(3);
	let priceNum = ref("");
	let title = ref("");
	let tags = ref([]);
	let total = ref(0);
	const sector = ref([]);
	const pageNum = ref(1);
	const pageSize = ref(5);
	const dateSearch = ref("");
	const titleName = ref("");
	const industry = ref([]);
	const tagIds = ref([]);
	let shows = ref(false);
	const dialogImageUrl = ref("");
	const dialogVisible = ref(false);
	const emailForm = reactive({
		test_msg: "",
		msg: ""
	});
	let port = reactive({
		tagList: [],
		articleList: [],
		list: []
	});
	let form = reactive({
		name: "",
		tags: [],
		subscription: "",
		introduction: "",
		description: "",
		industry: [],
		sector: [],
		clubImage: ""
	});
	onActivated(async () => {
		art.value = 1;
		if (clubId) {
			await echoClubs();
			await actiList();
		}
	});
	onMounted(async () => {
		await tagsList();
		await ArticleList();
		// 获取分类树
		await classFen();
		if (clubId) {
			await echoClubs();
			await actiList();
		}

		window.addEventListener("scroll", handleScroll);
	});
	// 置顶
	const pinneds = async item => {
		console.log(item, "66666666666666");
		let n = await PutArticleTheTop({ articleId: item.id });
		if (n.code == 200) {
			ElMessage.success(n.msg);
			actiList();
		}
	};
	// 鼠标移入
	const handleMouseOver = num => {
		indsValue.value = num;
	};
	// 鼠标移出
	const handleMouseLeave = num => {
		indsValue.value = -1;
	};
	// 点击删除
	const deletes = async item => {
		let n = await DeleteleEcho({ articleId: item.id });
		if (n.code == 200) {
			ElMessage.success(n.msg);
			actiList();
		}
	};
	// 搜索
	const sousuo = () => {
		actiList();
		filterVisible.value = false;
	};
	// 这个是获取文章列表
	const actiList = async () => {
		let n = await CreateArticleList({
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			clubId: clubId,
			dateSearch: time.value || "",
			title: marking.value || "",
			tagIds: formFilter.tags || [],
			minPrice: formFilter.min || "",
			maxPrice: formFilter.max || ""
		});
		total.value = n.data.total;

		handleArr(n.data.list);
	};
	// 选择时间
	const changeFn = e => {
		time.value = dayjs(+new Date(e)).format("YYYY-MM-DD");
	};
	// 去更新
	const edits = async item => {
		let n = await GetArticleEcho({ articleId: item.id });
		id.value = item.id;
		showPrice.value = n.data.free;
		imgCover.value = n.data.image;
		tags.value = n.data.tagIds;
		title.value = n.data.title;
		priceNum.value = n.data.price;
		richText.value.content = n.data.freeContent;
		richTexts.value.content = n.data.content;
		emailForm.test_msg = n.data.freeContent;
		emailForm.msg = n.data.content;
		publishTime.value = n.data.publishTime;
		fileList.value = [{ url: n.data.image }];

		console.log(richTexts.value, "5555555");
		art.value = 2;
		// let obj = {
		// 	clubId: clubId,
		// 	title: title.value,
		// 	tagIds: tags.value,
		// 	image: imgCover.value,
		// 	free: showPrice.value,
		// 	price: priceNum.value,
		// 	freeContent: richText.value.content,
		// 	content: richTexts.value.content,
		// 	publishTime: dayjs(+new Date()).format("YYYY-MM-DD HH:mm:ss")
		// };
		// richText.value.getContent();
		// console.log(richText.value.content, "8888");
		// router.push({
		// 	path: "/KnowCreateCkubDetils",
		// 	query: {
		// 		obj: JSON.stringify(obj)
		// 	}
		// });
	};
	// /去预览
	const priCount = () => {
		let obj = {};
		if (id.value) {
			obj = {
				id: id.value,
				clubId: clubId,
				title: title.value,
				tagIds: tags.value,
				image: imgCover.value,
				free: showPrice.value,
				price: priceNum.value,
				freeContent: richText.value.content,
				content: richTexts.value.content,
				publishTime: publishTime.value
			};
		} else {
			obj = {
				clubId: clubId,
				title: title.value,
				tagIds: tags.value,
				image: imgCover.value,
				free: showPrice.value,
				price: priceNum.value,
				freeContent: richText.value.content,
				content: richTexts.value.content,
				publishTime: dayjs(+new Date()).format("YYYY-MM-DD HH:mm:ss")
			};
		}
		// richText.value.getContent();
		// console.log(richText.value.content, "8888");
		router.push({
			path: "/KnowCreateCkubDetils",
			query: {
				obj: JSON.stringify(obj)
			}
		});
	};
	// 创建文章
	const saveArt = async () => {
		let obj = {
			clubId: clubId,
			title: title.value,
			tagIds: tags.value,
			image: imgCover.value,
			free: showPrice.value,
			price: priceNum.value,
			freeContent: richText.value.content,
			content: richTexts.value.content
			// publishTime: ""
		};
		let n = {};
		// 代表是修改
		if (id.value) {
			n = await UpdateArticles({ ...obj, id: id.value, publishTime: publishTime.value });
		} else {
			// 、代表是新增
			n = await CreateAnArticle(obj);
		}
		if (n.code == 200) {
			actiList();
			art.value = 1;
			id.value = 0;
			ElMessage.success(n.msg);
			title.value = "";
			tags.value = "";
			imgCover.value = "";
			showPrice.value = "";
			priceNum.value = "";
			richText.value.content = "";
			richTexts.value.content = "";
			fileList.value = [];
		}
	};
	// 上传成功的时候
	const successCover = e => {
		console.log(e, "6666666666666");
		imgCover.value = e.data;
	};
	// 切换
	const forFree = () => {
		showPrice.value = 1;
		priceNum.value = "";
	};

	// 处理数组函数
	const handleArr = data => {
		const result = data.reduce((acc, obj) => {
			const date = new Date(obj.publishTime);
			const month = date.toLocaleString("default", { month: "short" });
			if (!acc[month]) {
				acc[month] = []; // 创建一个空数组
			}
			acc[month].push(obj);

			return acc;
		}, {});

		const resultArray = Object.entries(result).map(([key, value]) => {
			return [key, value];
		});
		port.list = resultArray;
	};
	// 这个是回显数据
	const echoClubs = async () => {
		let n = await InformationAboutClubs({ clubId: clubId });
		if (n.data.industryOne) {
			chasngeSector(n.data.industryOne);
			// 表示工作
			form.sector = n.data.industryOne;
			form.industry = n.data.industry;
		}
		// console.log(port.tagList, "port.tagList");
		form.industry = n.data.industryTwo;
		form.tags = n.data.tagIds;
		form.name = n.data.clubName;
		form.subscription = n.data.subscription;
		form.discount = n.data.discount;
		form.introduction = n.data.introduction;
		form.description = n.data.description;
		form.clubImage = n.data.clubImage;
		if (n.data.discountMonths) {
			Monthly.value = n.data.discountMonths + "months";
		}
	};
	// 点击保存创建俱乐部
	const saveBao = async () => {
		let obj = {
			industryOne: form.sector,
			industryTwo: form.industry,
			clubName: form.name,
			clubImage: form.clubImage, //俱乐部封面图
			tagIds: form.tags, //俱乐部标签
			subscription: form.subscription, //价格单月
			discount: form.discount, //折扣价格
			discountMonths: form.discount ? MonthlyNum.value : "", //折扣月份  3 三个月   6六个月  12 十二个月
			introduction: form.introduction, //说明
			description: form.description //描述
		};
		if (clubId) {
			let n = await UpdateTheClub({ ...obj, id: clubId });
			if (n.code == 200) {
				ElMessage.success(n.msg);
			}
		} else {
			let n = await SellCreateClub(obj);
			if (n.code == 200) {
				ElMessage.success(n.msg);
				setTimeout(() => {
					router.go(-1);
				}, 500);
			}
		}
	};
	const tagsList = async () => {
		let n = await SellTagsList({ pageNum: 1, pageSize: 200, type: 1 });
		port.tagList = n.data.list;
		port.tagList.forEach(item => {
			item.value = item.id;
			item.label = item.name;
		});
	};
	// 文章tags
	const ArticleList = async () => {
		let n = await SellTagsList({ pageNum: 1, pageSize: 200, type: 2 });
		port.articleList = n.data.list;
		port.articleList.forEach(item => {
			item.value = item.id;
			item.label = item.name;
		});
	};
	// 获取分一级类树
	const classFen = async () => {
		industry.value = [];
		let n = await ClassificationTree();
		sector.value = n.data;
		sector.value.forEach(item => {
			// if (item.children) {
			item.value = item.id;
			item.children.forEach(ite => {
				ite.value = ite.id;
			});
			// }
		});
	};
	// 分类树二级选择
	const chasngeSector = e => {
		form.industry = "";
		let list = sector.value.filter(item => item.id == e);
		if (list[0] && list[0].children) {
			industry.value = list[0].children;
		} else {
			industry.value = {};
		}
	};
	const cler = () => {
		formFilter.min = "";
		formFilter.max = "";
		formFilter.tags = [];
		formFilter.dataTime = "";
		time.value = "";
		marking.value = "";
		actiList();
	};

	// 点击分页
	const currentChange = e => {
		pageNum.value = e;
		actiList();
	};
	// 点击第二个导航
	const tow = () => {
		ind.value = 2;
		art.value = 1;
	};
	//点击添加
	const addAct = () => {
		id.value = 0;
		ind.value = 2;
		art.value = 2;
	};
	// 上传成功时的钩子
	const successImg = (e, s) => {
		form.clubImage = e.data;
		console.log("上传成功", e, "111111111111111111111111111111");
	};
	const getMsg = val => {
		emailForm.test_msg = val;
		console.log(val, "151515151");
	};
	const getMsgs = val => {
		emailForm.msg = val;
		console.log(val, "151515151");
	};
	const qiehuan = item => {
		shows.value = false;
		MonthlyNum.value = item;
		Monthly.value = item + " Monthly";
	};
	// 这个是当头部导航栏滑倒下面时给tabr加个背景
	const handleScroll = () => {
		const scrollTop = document.documentElement.scrollTop;
		if (scrollTop > 0) {
			statusTab.value = 2;
		} else {
			statusTab.value = 1;
		}
	};
</script>
<style scoped>
	@import "./index.scss";
	::v-deep .el-pager li:hover {
		color: #000000 !important;
	}

	::v-deep .el-pager li.is-active {
		color: #000000 !important;
	}

	::v-deep .el-pagination button:hover {
		color: #000000 !important;
	}

	::v-deep .el-pager li {
		font-size: px(24) !important;
		margin: 0 8px;
	}

	::v-deep .el-pagination .btn-next .el-icon {
		font-size: 20px !important;
	}

	::v-deep .el-pagination .btn-prev .el-icon {
		font-size: 20px !important;
	}
</style>
